package top.fengyulou.xiaofeng.controller.admin;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.net.NetUtil;
import cn.hutool.poi.word.Word07Writer;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xwpf.usermodel.ParagraphAlignment;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import top.fengyulou.xiaofeng.common.*;
import top.fengyulou.xiaofeng.dto.ClassifyDto;
import top.fengyulou.xiaofeng.dto.LabelDto;
import top.fengyulou.xiaofeng.dto.QuestionDto;
import top.fengyulou.xiaofeng.dto.QuestionOptionDto;
import top.fengyulou.xiaofeng.enums.DataTypeEnum;
import top.fengyulou.xiaofeng.enums.QuestionTypeEnum;
import top.fengyulou.xiaofeng.service.ClassifyService;
import top.fengyulou.xiaofeng.service.LabelService;
import top.fengyulou.xiaofeng.service.QuestionService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 后台用户管理
 */
@Controller
public class AdminQuestionController {

    @Resource
    private QuestionService questionService;
    @Resource
    private LabelService labelService;
    @Resource
    private ClassifyService classifyService;

    /**
     * 列表页面
     */
    @RequestMapping("/admin/question/list")
    public String list() {
        return "admin/question/admin-question-list";
    }

    /**
     * 试题导出Word
     */
    @RequestMapping("/admin/question/exportWord")
    public void exportWord(String ids, HttpServletResponse response) throws IOException {
        Word07Writer writer = new Word07Writer();
        String[] idArr = ids.split(",");
        for (int i = 0; i < idArr.length; i++) {
            String id = idArr[i];
            QuestionDto question = questionService.getByIdExtend(id);
            writer.addText(new Font("宋体", Font.PLAIN, 14), (i + 1) + "、[" + MyUtils.qstTypeMap.get(question.getType()) + "]" + question.getContent());
            if (!question.getType().equals(QuestionTypeEnum.ZHUGUAN.getCode())) {
                for (int i1 = 0; i1 < question.getOptionDtoList().size(); i1++) {
                    QuestionOptionDto questionOptionDto = question.getOptionDtoList().get(i1);
                    writer.addText(new Font("宋体", Font.PLAIN, 14), CommonUtils.tabIndent(1) + questionOptionDto.getOption() + "、" + questionOptionDto.getContent());
                }
                writer.addText(new Font("宋体", Font.PLAIN, 14), "试题答案：" + question.getAnswer());
            }
            writer.addText(new Font("宋体", Font.PLAIN, 14), "试题解析：" + question.getAnalysis());
            writer.addText(new Font("宋体", Font.PLAIN, 14), "");
        }
        WebUtils.dowWordFile(response, System.currentTimeMillis() + "", writer);
    }

    /**
     * 列表查询
     */
    @RequestMapping("/admin/question/ajax/list")
    @ResponseBody
    public Jr list(@RequestBody QuestionDto questionDto) {
        questionService.list(questionDto);
        return Jr.yesd(questionDto);
    }

    //编辑页面
    @RequestMapping("/admin/question/save")
    public String save(String id, Model model) {
        if (StringUtils.isNotBlank(id)) {
            QuestionDto question = questionService.getByIdExtend(id);
            model.addAttribute("data", question);
        }
        //标签列表
//        LabelDto labelDto = new LabelDto();
//        labelDto.setDataType(DataTypeEnum.QST.getCode());
//        List<LabelDto> labelList = labelService.list(labelDto);
//        model.addAttribute("labelList", labelList);
        //分类列表
        ClassifyDto classifyDto = new ClassifyDto();
        classifyDto.setDataType(DataTypeEnum.QST.getCode());
        List<ClassifyDto> classifyList = classifyService.list(classifyDto);
        model.addAttribute("classifyList", classifyList);
        return "admin/question/admin-question-save";
    }

    /**
     * 保存，id有值时更新，无值时新增
     */
    @RequestMapping("/admin/question/ajax/save")
    @ResponseBody
    public Jr ajaxSave(HttpServletRequest request, QuestionDto questionDto) {
        questionDto.setCurrentUserId(UserUtils.getUserId(request));
        questionService.save(questionDto);
        return Jr.yesd(questionDto);
    }

    /**
     * 删除
     */
    @RequestMapping("/admin/question/ajax/delete")
    @ResponseBody
    public Jr ajaxDelete(HttpServletRequest request, @RequestParam String[] ids) {
        questionService.delete(ids);
        return Jr.yes();
    }

    //导入试题
    @RequestMapping("/admin/question/ajax/import")
    @ResponseBody
    public Jr ajaxImport(HttpServletRequest request) {
        /*try {
            importQuestion(questionList("11. 摸底测试”"),UserUtils.getUserId(request));
            importQuestion(questionList("8. 12-13章直播+“周周测”"),UserUtils.getUserId(request));
            importQuestion(questionList("7. 10-11章直播+“周周测”"),UserUtils.getUserId(request));
            importQuestion(questionList("5. 8-9章直播+“周周测”"),UserUtils.getUserId(request));
            importQuestion(questionList("4. 6-7章直播+“周周测”"),UserUtils.getUserId(request));
            importQuestion(questionList("4. 4-5章直播+“周周测”"),UserUtils.getUserId(request));
            importQuestion(questionList("3. 1-3章直播+“周周测”"),UserUtils.getUserId(request));
            importQuestion(questionList("2. 摸底测试"),UserUtils.getUserId(request));
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        return Jr.yes();
    }

    /**
     * 导入试题
     *
     * @param questionList
     */
    public void importQuestion(List<QuestionDto> questionList, String userId) {
        for (QuestionDto questionDto : questionList) {
            questionDto.setCreateUserId(userId);
            questionService.save(questionDto);
        }
    }

    //解析html
    public List<QuestionDto> questionList(String name) throws IOException {
        List<QuestionDto> questionList = new ArrayList<>();
        String html = FileUtils.readFileToString(new File("G:\\gitee\\exam\\src\\main\\resources\\templates\\光环周周测试题\\" + name + ".html"), "UTF-8");
        // 解析字符串
        Document document = Jsoup.parse(html);
        Elements elements = document.select(".question-container .item-wrap");
        System.out.println("題目: " + elements.size());
        System.out.println("-----------------------------------------------");
        for (Element element : elements) {
            QuestionDto questionDto = new QuestionDto();
            questionDto.setType(QuestionTypeEnum.DANXUAN.getCode());
            //题目
            Elements questions = element.select(".question-wrap .question-title #detail_div");
            for (Element question : questions) {
                System.out.println(question.html());
                questionDto.setContent(question.html());
            }
            //选项
            Elements options = element.select(".option-item-after .my-item-wrap-option #detail_div");
            System.out.println("选项: " + options.size());
            List<QuestionOptionDto> optionList = new ArrayList<>();
            for (int i = 0; i < options.size(); i++) {
                Element option = options.get(i);
                System.out.println(option.html());
                QuestionOptionDto questionOptionDto = new QuestionOptionDto();
                questionOptionDto.setOption(MyUtils.OPTIONS[i]);
                questionOptionDto.setContent(option.html());
                optionList.add(questionOptionDto);
                questionDto.setOptionDtoList(optionList);
            }
            //正确答案
            Elements answers = element.select(".answer-wrap .right-answer");
            for (Element answer : answers) {
                System.out.println(answer.html());
                questionDto.setAnswer(answer.html());
            }
            //解析
            Elements analyses = element.select(".answer-wrap #detail_div");
            for (Element analysis : analyses) {
                System.out.println(analysis.html());
                questionDto.setAnalysis(analysis.html());
            }
            System.out.println(JSONObject.toJSONString(questionDto));
            questionList.add(questionDto);
            System.out.println("-----------------------------------------------");
        }
        return questionList;
    }

    //树列表
    @RequestMapping("/admin/question/classify/tree/list")
    public String treeList(ClassifyDto classifyDto, Model model) {
        model.addAttribute("query", classifyDto);
        model.addAttribute("dataType", DataTypeEnum.QST.getCode());
        return "admin/classify/admin-classify-tree-list";
    }

    //编辑页面
    @RequestMapping("/admin/question/classify/save")
    public String classifySave(String id, Model model) {
        if (StringUtils.isNotBlank(id)) {
            ClassifyDto classify = classifyService.getById(id);
            model.addAttribute("data", classify);
        }
        model.addAttribute("dataType", DataTypeEnum.QST.getCode());
        return "admin/classify/admin-classify-save";
    }
}
